该博文的目的是对C++类的概念的理解.

设计CBook类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class CBook {
public:
CBook() {}
~CBook() {}
CBook(char *cName, char *clsbn, char *cPrice, char *cAuthor);

public:
void WriteData();
void DeleteDate(int iCount);
void GetBookFromFile(int iCount);

protected:
char m_cName[NUM1];
char m_clsbn[NUM1];
char m_cPrice[NUM2];
char m_cAuthor[NUM2];
};

拷贝构造函数函数的实现

1
2
3
4
5
6
CBook::CBook(char *cName, char *clsbn, char *cPrice, char *cAuthor) {
strncpy(m_cName, cName, NUM1);
strncpy(m_clsbn, clsbn, NUM1);
strncpy(m_cPrice, cPrice, NUM2);
strncpy(m_cAuthor, cAuthor, NUM2);
}

添加模块

1
2
3
4
5
6
7
8
9
10
11
12
13
14
void CBook::WriteData() {
ofstream ofile;
ofile.open("book.dat", ios::binary | ios::app);
try {
ofile.write(m_cName, NUM1);
ofile.write(m_clsbn, NUM1);
ofile.write(m_cPrice, NUM2);
ofile.write(m_cAuthor, NUM2);
} catch (...) {
throw "file error occurred ";
ofile.close();
}
ofile.close();
}

删除模块

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
void CBook::DeleteDate(int iCount) {
long respos;
int iDataCount = 0;
fstream file;
fstream tmpfile;
ofstream ofile;
char cTempBuf[NUM1 + NUM1 + NUM2 + NUM2];
file.open("book.dat", ios::binary | ios::in | ios::out);
tmpfile.open("temp.dat", ios::binary | ios::in | ios::out | ios::trunc);
file.seekg(0, ios::end);
respos = file.tellg();
iDataCount = respos / (NUM1 + NUM1 + NUM2 + NUM2);
if (iCount < 0 && iCount > iDataCount) {
throw "Input number error";
} else {
file.seekg((iCount) * (NUM1 + NUM1 + NUM2 + NUM2), ios::beg);
for (int j = 0; j < (iDataCount - iCount); j++) {
memset(cTempBuf, 0, NUM1 + NUM1 + NUM2 + NUM2);
file.read(cTempBuf, NUM1 + NUM1 + NUM2 + NUM2);
tmpfile.write(cTempBuf, NUM1 + NUM1 + NUM2 + NUM2);
}
file.close();
tmpfile.seekg(0, ios::beg);
ofile.open("book.dat");
ofile.seekp((iCount - 1) * (NUM1 + NUM1 + NUM2 + NUM2), ios::beg);
for (int i = 0; i < (iDataCount - iCount); i++) {
memset(cTempBuf, 0, NUM1 + NUM1 + NUM2 + NUM2);
tmpfile.read(cTempBuf, NUM1 + NUM1 + NUM2 + NUM2);
ofile.write(cTempBuf, NUM1 + NUM1 + NUM2 + NUM2);
}
}
tmpfile.close();
ofile.close();
remove("temp.dat");
}

浏览模块

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
void CBook::GetBookFromFile(int iCount) {
char cName[NUM1];
char clsbn[NUM1];
char cPrice[NUM2];
char cAuthor[NUM2];
ifstream ifile; //这里创建了一个ifile输入流
ifile.open("book.dat", ios::binary);
try {
ifile.seekg(iCount * (NUM1 + NUM1 + NUM2 + NUM2), ios::beg);
ifile.read(cName, NUM1);
// char * strncpy ( char * destination, const char * source, size_t num );
if (ifile.tellg() > 0)
strncpy(m_cName, cName, NUM1);
ifile.read(clsbn, NUM1);
if (ifile.tellg() > 0)
strncpy(m_clsbn, clsbn, NUM1);
ifile.read(cPrice, NUM2);
if (ifile.tellg() > 0)
strncpy(m_cPrice, cPrice, NUM2);
ifile.read(cAuthor, NUM2);
if (ifile.tellg() > 0)
strncpy(m_cAuthor, cAuthor, NUM2);
} catch (...) {
throw "file error occurred";
ifile.close();
}
ifile.close();
}

待续